package com.wt.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wt.order.common.BaseContext;
import com.wt.order.common.CustomException;
import com.wt.order.entity.*;
import com.wt.order.mapper.OrdersMapper;
import com.wt.order.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.ParameterResolutionDelegate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author 吴涛
 * @date 2022/5/17 19:09
 * @qq 337144203
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private UserService userService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;


    /**
     * 下单
     * @param orders
     */
    public void saveOrder(Orders orders) {
//        A. 获得当前用户id, 查询当前用户的购物车数据
        Long userId = BaseContext.getCurrentId();

        LambdaQueryWrapper<ShoppingCart> shoppingQueryWrapper = new LambdaQueryWrapper<>();
        shoppingQueryWrapper.eq(ShoppingCart::getUserId, userId);
        //查出购物车中的数据
        List<ShoppingCart> shoppingCartslist = shoppingCartService.list(shoppingQueryWrapper);
        //判断购物车是否为空,空的话就不能下单，抛出一个异常
        if (shoppingCartslist == null && shoppingCartslist.size() == 0) {
            throw new CustomException("购物车为空，不能下单");

        }

        //        B. 根据当前登录用户id, 查询用户数据
        User user = userService.getById(userId);

//        C. 根据地址ID, 查询地址数据
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        //判断地地址是否为空
        if (addressBook == null) {
            throw new CustomException("配送地址为空，请选择地址后再试");
        }

//        D. 组装订单明细数据, 批量保存订单明细
        long orderId = IdWorker.getId();

        AtomicInteger amount = new AtomicInteger(0);
        List<OrderDetail> orderDetails = shoppingCartslist.stream().map((wt) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(wt.getNumber());
            orderDetail.setDishFlavor(wt.getDishFlavor());
            orderDetail.setSetmealId(wt.getSetmealId());
            orderDetail.setName(wt.getName());
            orderDetail.setDishId(wt.getDishId());
            orderDetail.setAmount(wt.getAmount());
            orderDetail.setImage(wt.getImage());
            amount.addAndGet(wt.getAmount().multiply(new BigDecimal(wt.getNumber())).intValue());
            return orderDetail;

        }).collect(Collectors.toList());


        //        E. 组装订单数据, 批量保存订单数据
        orders.setId(orderId);
        orders.setUserId(userId);
        orders.setStatus(2);

        //下单日期和时间
        orders.setOrderTime(LocalDateTime.now());
        //总的金额
        orders.setAmount(new BigDecimal(amount.get()));
        orders.setCheckoutTime(LocalDateTime.now());//支付时间
        orders.setNumber(String.valueOf(orderId));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());//收货人
        orders.setUserName(user.getName());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //保存
        this.save(orders);
        orderDetailService.saveBatch(orderDetails);

//        F. 删除当前用户的购物车列表数据
        shoppingCartService.remove(shoppingQueryWrapper);
    }



}
